package com.wing.purchase.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.product.service.DynamicService;
import com.wing.product.service.ProductPackLabelService;
import com.wing.purchase.dao.PurchaseDeliveryRecordDao;
import com.wing.purchase.dao.PurchaseDeliveryRecordProductDao;
import com.wing.purchase.dao.PurchaseSignForDao;
import com.wing.purchase.model.entity.*;
import com.wing.purchase.model.request.PurchaseSignForForm;
import com.wing.purchase.model.response.*;
import com.wing.purchase.util.PurchaseSignUtil;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 采购签收-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurchaseSignForServiceImpl extends ServiceImpl<PurchaseSignForDao, PurchaseSignFor> implements PurchaseSignForService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private PurchaseSignForProductService purchaseSignForProductService;
    @Autowired
    private PurchaseWarehousingPlanService purchaseWarehousingPlanService;
    @Autowired
    private PurchaseWarehousingPlanProductService purchaseWarehousingPlanProductService;
    @Autowired
    private ProductPackLabelService productPackLabelService;
    @Autowired
    private PurchaseSignForProductLabelService purchaseSignForProductLabelService;

    @Autowired
    private PurchaseDeliveryRecordDao purchaseDeliveryRecordDao;

    @Autowired
    private PurchaseDeliveryRecordProductDao purchaseDeliveryRecordProductDao;


    @Override
    @Transactional(readOnly = false)
    public JsonResult add(PurchaseSignForForm purchaseSignForForm) {

 /*       if(StringUtils.isBlank(purchaseSignForForm.getSignTaskId())){
            return JsonResult.fail("签收任务编号为空，可能已经签收过，请检查！");
        }
*/
        //校验
        PurchaseSignFor purchaseSignFor = new PurchaseSignFor();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseSignFor.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseSignForForm, purchaseSignFor, copyOptions);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("sign_no", "pur_purchase_sign_for");
        String day = simpleDateFormat.format(new Date());
        purchaseSignFor.setSignNo("PS" + day + code);

        //TODO 校验相关数量是否超出
        for (PurchaseSignForProduct purchaseSignForProduct : purchaseSignForForm.getPurchaseSignForProducts()) {
            //校验数量是否为空 或者 为null
            BigDecimal signNum = purchaseSignForProduct.getSignNum();

            if (signNum == null || signNum.signum() <= 0) {
                // 当 signNum 为 null 或者小于等于 0 时执行的逻辑
                return JsonResult.fail("存在 签收数量为0或者未填写，请确认后在重新提交！");
            }

        }


        //签收类型
        if(PurchaseSignUtil.CGR.equals(purchaseSignForForm.getInventoryTypeCode())){
            //采购入库
            purchaseSignFor.setSignBusinessType("1"); //采购入库单
            List<PurchaseDeliveryRecordProductVO> purchaseDeliveryRecordProduct = purchaseDeliveryRecordProductDao.getPurchaseDeliveryRecordProduct(purchaseSignForForm.getId());
            //进行校验  签收数量是否大于 采购数量
            if(purchaseDeliveryRecordProduct.size()>0){
                for (PurchaseDeliveryRecordProductVO purchaseDeliveryRecordProductVO : purchaseDeliveryRecordProduct) {
                    for (PurchaseSignForProduct purchaseSignForProduct : purchaseSignForForm.getPurchaseSignForProducts()) {
                        if (purchaseSignForProduct.getSignProductId() != null && purchaseDeliveryRecordProductVO.getId() != null) {
                            if(purchaseSignForProduct.getSignProductId().equals(purchaseDeliveryRecordProductVO.getId())){
                                //发货数量-签收数  =剩余签收数
                                // 剩余签收数量 >= 当前签收数  就可以签收
                                BigDecimal surplusCount = purchaseDeliveryRecordProductVO.getQuantity().subtract(purchaseDeliveryRecordProductVO.getHasSignQuantity());
                                if (surplusCount.compareTo(BigDecimal.ZERO) < 0) {
                                    return JsonResult.fail("存在签收数量  大于 剩余签收数量 不可以继续签收，提交失败");
                                }
                                if (purchaseSignForProduct.getSignNum().compareTo(surplusCount) > 0) {
                                    //当前签收数量  大于 剩余签收数量 不可以继续签收 提示前台
                                    return JsonResult.fail("存在签收数量  大于 剩余签收数量 不可以继续签收，提交失败");
                                }



                            }
                        }

                    }
                }
            }
        }else if(PurchaseSignUtil.SCR.equals(purchaseSignForForm.getInventoryTypeCode())){
            //生产入库
            purchaseSignFor.setSignBusinessType("3"); //生产报工单
            List<ProductionTheWorkOrderVO> productionInfo = baseMapper.getProductionInfo(purchaseSignForForm.getId());
            for (PurchaseSignForProduct purchaseSignForProduct : purchaseSignForForm.getPurchaseSignForProducts()) {
               for (ProductionTheWorkOrderVO productionTheWorkOrderVO : productionInfo) {
                     //判断是同一个产品
                     if(productionTheWorkOrderVO.getId().equals(purchaseSignForProduct.getSignProductId())){
                         Integer surplusCount = productionTheWorkOrderVO.getWorkQuantity()-(productionTheWorkOrderVO.getSignedNum());
                         if(surplusCount<=0){
                             return JsonResult.fail("存在签收数量  大于 剩余签收数量 不可以继续签收，提交失败");
                         }
                         if (purchaseSignForProduct.getSignNum().compareTo(new BigDecimal(surplusCount)) > 0) {
                             //当前签收数量  大于 剩余签收数量 不可以继续签收 提示前台
                             return JsonResult.fail("存在签收数量  大于 剩余签收数量 不可以继续签收，提交失败");
                         }
                     }
                 }

            }
       }




        purchaseSignFor.setSignSkuNum(purchaseSignForForm.getPurchaseSignForProducts().size()); //签收物料数量
        purchaseSignFor.setStatus("1"); //签收状态 待确认
        purchaseSignFor.setCheckStatus("1"); //质检状态 待取样
        int i = baseMapper.insert(purchaseSignFor);
        if (i > 0) {
            for (PurchaseSignForProduct purchaseSignForProduct : purchaseSignForForm.getPurchaseSignForProducts()) {
                purchaseSignForProduct.setPurchaseSignForId(purchaseSignFor.getId());
            }
            purchaseSignForProductService.saveBatch(purchaseSignForForm.getPurchaseSignForProducts());


            if(PurchaseSignUtil.CGR.equals(purchaseSignForForm.getInventoryTypeCode())){
                //TODO 签收完成改变 供应商发货记录 状态为已签收
                List<PurchaseDeliveryRecordProductVO> purchaseDeliveryRecordList = purchaseDeliveryRecordProductDao.getPurchaseDeliveryRecordList(purchaseSignForForm.getId());
                //如果多个值都是已签收数量和采购数量一致，则改变状态为已签收
                Boolean flag=false;
                for (PurchaseDeliveryRecordProductVO purchaseDeliveryRecordProductVO : purchaseDeliveryRecordList) {
                    //已经签收数量
                    BigDecimal hasSignQuantity = purchaseDeliveryRecordProductVO.getHasSignQuantity();
                    BigDecimal purchaseQuantity = purchaseDeliveryRecordProductVO.getPurchaseQuantity();
                    // 使用 compareTo 方法比较两个 BigDecimal 对象
                    if (hasSignQuantity != null && purchaseQuantity != null && hasSignQuantity.compareTo(purchaseQuantity) == 0) {
                        // 两个值相等的情况
                        flag=true;
                    } else if (hasSignQuantity == null || purchaseQuantity == null) {
                        // 处理可能的 null 值情况
                        flag=false;
                    } else {
                        // 两个值不相等的情况
                        flag=false;
                    }
                }
                if(flag){
                    purchaseDeliveryRecordDao.updatePurchaseDeliveryStatus(purchaseSignForForm.getId(),"2");
                }
            }

            return JsonResult.success("添加成功");
        }else{
            return JsonResult.fail("添加失败");
        }
    }

    @Override
    @Transactional(readOnly = false)
    public boolean update(PurchaseSignFor purchaseSignFor) {
        int i = baseMapper.updateById(purchaseSignFor);
        if (i > 0) {
            List<PurchaseSignForProduct> addDetails = new ArrayList<>();
            List<PurchaseSignForProduct> updDetails = new ArrayList<>();
            List<Long> delDetails = new ArrayList<>();
            List<Long> ids = new ArrayList<>();
            for (PurchaseSignForProduct purchaseSignForProduct : purchaseSignFor.getPurchaseSignForProducts()) {
                if (null == purchaseSignForProduct.getId()) {
                    purchaseSignForProduct.setCreator(JwtUtils.getLoginUserId());
                    purchaseSignForProduct.setCreatorName(JwtUtils.getLoginUsername());
                    purchaseSignForProduct.setModifier(JwtUtils.getLoginUserId());
                    purchaseSignForProduct.setModifierName(JwtUtils.getLoginUsername());
                    purchaseSignForProduct.setPurchaseSignForId(purchaseSignFor.getId());
                    addDetails.add(purchaseSignForProduct);
                } else {
                    ids.add(purchaseSignForProduct.getId());
                    updDetails.add(purchaseSignForProduct);
                }
            }
            // 查询旧数据
            List<PurchaseSignForProduct> oldDetails = purchaseSignForProductService.list(new QueryWrapper<PurchaseSignForProduct>().eq("purchase_sign_for_id", purchaseSignFor.getId()));
            for (PurchaseSignForProduct oldDetail : oldDetails) {
                if (!ids.contains(oldDetail.getId())) {
                    delDetails.add(oldDetail.getId());
                }
            }
            if (addDetails.size() > 0) {
                purchaseSignForProductService.saveBatch(addDetails);
            }
            if (updDetails.size() > 0) {
                purchaseSignForProductService.updateBatchById(updDetails);
            }
            if (delDetails.size() > 0) {
                purchaseSignForProductService.removeByIds(delDetails);
            }
        }
        return i > 0;
    }

    @Override
    public List<PurchaseSignForVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<PurchaseSignForVO> pageList4app(Page page, Map<String, Object> params) {
        //采购-发货记录列表
        Map<String, Object> purchaseDeliveryRecordMap = new HashMap<>();
        purchaseDeliveryRecordMap.put("databaseUser", params.get("databaseUser"));
        List<PurchaseDeliveryRecordVO> purchaseDeliveryRecordList = purchaseDeliveryRecordDao.list4app(null, purchaseDeliveryRecordMap);
        //生产-报工单信息
        Map<String, Object> productionTheWorkOrderMap = new HashMap<>();
        productionTheWorkOrderMap.put("databaseUser", params.get("databaseUser"));
        List<ProductionTheWorkOrderVO> productionTheWorkOrderList = baseMapper.productionWorkOrderList(productionTheWorkOrderMap);
        Map<Long, ProductionTheWorkOrderVO> workOrderMap = productionTheWorkOrderList.stream()
                .collect(Collectors.toMap(ProductionTheWorkOrderVO::getId, Function.identity()));



        List<PurchaseSignForVO> listBig=new ArrayList<>();
        //签收记录列表
        List<PurchaseSignForVO> list = baseMapper.list4app(page, params);
        for (PurchaseSignForVO purchaseSignFor : list) {
            //采购-发货记录信息
            if (PurchaseSignUtil.CGR.equals(purchaseSignFor.getInventoryTypeCode())) {
                PurchaseDeliveryRecordVO purchaseDeliveryRecord = purchaseDeliveryRecordList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);
                if(purchaseDeliveryRecord != null){
                    purchaseSignFor.setLogisticsNo(purchaseDeliveryRecord.getLogisticsNo());
                    purchaseSignFor.setSupplierId(purchaseDeliveryRecord.getSupplierId());
                    purchaseSignFor.setSn(purchaseDeliveryRecord.getSn());
                    purchaseSignFor.setCorporateCode(purchaseDeliveryRecord.getCorporateCode());
                    purchaseSignFor.setCorporateName(purchaseDeliveryRecord.getCorporateName());
                    purchaseSignFor.setTransportMode(purchaseDeliveryRecord.getTransportMode());
                    purchaseSignFor.setTransportModeDesc(purchaseDeliveryRecord.getTransportModeDesc());
                    purchaseSignFor.setLogisticsCompany(purchaseDeliveryRecord.getLogisticsCompany());
                    purchaseSignFor.setEnterType(purchaseDeliveryRecord.getEnterType());
                    purchaseSignFor.setEnterTypeName(purchaseDeliveryRecord.getEnterTypeName());
                    purchaseSignFor.setDeliveryCreatorName(purchaseDeliveryRecord.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(purchaseDeliveryRecord.getCreateTime());
                    purchaseSignFor.setWaybillNo(purchaseDeliveryRecord.getWaybillNo());
                    purchaseSignFor.setPlateNo(purchaseDeliveryRecord.getPlateNo());
                    purchaseSignFor.setCourierNo(purchaseDeliveryRecord.getCourierNo());
                    purchaseSignFor.setPhone(purchaseDeliveryRecord.getPhone());
                    purchaseSignFor.setBusinessContact(purchaseDeliveryRecord.getBusinessContact());
                    purchaseSignFor.setDepartmentName(purchaseDeliveryRecord.getDepartmentName());
                    purchaseSignFor.setPurchaseApplicant(purchaseDeliveryRecord.getPurchaseApplicant());
                    purchaseSignFor.setAuditorName(purchaseDeliveryRecord.getAuditorName());
                    purchaseSignFor.setTotalAmount(purchaseDeliveryRecord.getTotalAmount());
                    listBig.add(purchaseSignFor);
                }else{
                    listBig.add(purchaseSignFor);
                }
             }else if(PurchaseSignUtil.SCR.equals(purchaseSignFor.getInventoryTypeCode())){  ///生产-报工单信息
/*
               ProductionTheWorkOrderVO productionWorkOrder = productionTheWorkOrderList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);
*/
                ProductionTheWorkOrderVO productionWorkOrder = workOrderMap.get(purchaseSignFor.getSignTaskId());
                if(productionWorkOrder!=null){
                    purchaseSignFor.setLogisticsNo(productionWorkOrder.getCode());
                    purchaseSignFor.setSn(productionWorkOrder.getWorkOrderCode());
                    purchaseSignFor.setSupplierId(productionWorkOrder.getRoleId());
                    purchaseSignFor.setCorporateCode(productionWorkOrder.getRoleCode());
                    purchaseSignFor.setCorporateName(productionWorkOrder.getRoleName());
                    purchaseSignFor.setDeliveryCreatorName(productionWorkOrder.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(productionWorkOrder.getCreateTime());
                    purchaseSignFor.setPhone(productionWorkOrder.getPhone());
                    purchaseSignFor.setBusinessContact(productionWorkOrder.getUsername());
                    purchaseSignFor.setDepartmentName(productionWorkOrder.getRoleName());
                    listBig.add(purchaseSignFor);
                }else{
                    listBig.add(purchaseSignFor);
                }
            }else{
                listBig.add(purchaseSignFor);
            }
        }
        // 使用原始Page对象的总数信息
        Page<PurchaseSignForVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(listBig);

        return resultPage;
    }


    /**
     * 触发时间的时候使用 前端入库作业的时候
     * @param page
     * @param params
     * @return
     */
    @Override
    public Page<PurchaseSignForVO> pageListChange4app(Page page, Map<String, Object> params) {
        //采购-发货记录列表
        Map<String, Object> purchaseDeliveryRecordMap = new HashMap<>();
        purchaseDeliveryRecordMap.put("databaseUser", params.get("databaseUser"));
        List<PurchaseDeliveryRecordVO> purchaseDeliveryRecordList = purchaseDeliveryRecordDao.list4app(null, purchaseDeliveryRecordMap);
        Map<Long, PurchaseDeliveryRecordVO> workOrderMap1 = purchaseDeliveryRecordList.stream()
                .collect(Collectors.toMap(PurchaseDeliveryRecordVO::getId, Function.identity()));


        //生产-报工单信息
        Map<String, Object> productionTheWorkOrderMap = new HashMap<>();
        productionTheWorkOrderMap.put("databaseUser", params.get("databaseUser"));
        List<ProductionTheWorkOrderVO> productionTheWorkOrderList = baseMapper.productionWorkOrderList(productionTheWorkOrderMap);
        Map<Long, ProductionTheWorkOrderVO> workOrderMap = productionTheWorkOrderList.stream()
                .collect(Collectors.toMap(ProductionTheWorkOrderVO::getId, Function.identity()));

        List<PurchaseSignForVO> listBig=new ArrayList<>();
        //将已签收的都拿出来
        params.put("status", 2);
        //签收记录列表2
        List<PurchaseSignForVO> list = baseMapper.list4app(page, params);
        for (PurchaseSignForVO purchaseSignFor : list) {
            //采购-发货记录信息
            if (PurchaseSignUtil.CGR.equals(params.get("inventoryTypeCode"))) {
                /*       if (PurchaseSignUtil.CGR.equals(purchaseSignFor.getInventoryTypeCode())) {*/
/*
                PurchaseDeliveryRecordVO purchaseDeliveryRecord = purchaseDeliveryRecordList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);
*/
                PurchaseDeliveryRecordVO purchaseDeliveryRecord = workOrderMap1.get(purchaseSignFor.getSignTaskId());
                if(purchaseDeliveryRecord != null){
                    purchaseSignFor.setLogisticsNo(purchaseDeliveryRecord.getLogisticsNo());
                    purchaseSignFor.setSupplierId(purchaseDeliveryRecord.getSupplierId());
                    purchaseSignFor.setSn(purchaseDeliveryRecord.getSn());
                    purchaseSignFor.setCorporateCode(purchaseDeliveryRecord.getCorporateCode());
                    purchaseSignFor.setCorporateName(purchaseDeliveryRecord.getCorporateName());
                    purchaseSignFor.setTransportMode(purchaseDeliveryRecord.getTransportMode());
                    purchaseSignFor.setTransportModeDesc(purchaseDeliveryRecord.getTransportModeDesc());
                    purchaseSignFor.setLogisticsCompany(purchaseDeliveryRecord.getLogisticsCompany());
                    purchaseSignFor.setEnterType(purchaseDeliveryRecord.getEnterType());
                    purchaseSignFor.setEnterTypeName(purchaseDeliveryRecord.getEnterTypeName());
                    purchaseSignFor.setDeliveryCreatorName(purchaseDeliveryRecord.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(purchaseDeliveryRecord.getCreateTime());
                    purchaseSignFor.setWaybillNo(purchaseDeliveryRecord.getWaybillNo());
                    purchaseSignFor.setPlateNo(purchaseDeliveryRecord.getPlateNo());
                    purchaseSignFor.setCourierNo(purchaseDeliveryRecord.getCourierNo());
                    purchaseSignFor.setPhone(purchaseDeliveryRecord.getPhone());
                    purchaseSignFor.setBusinessContact(purchaseDeliveryRecord.getBusinessContact());
                    purchaseSignFor.setDepartmentName(purchaseDeliveryRecord.getDepartmentName());
                    purchaseSignFor.setPurchaseApplicant(purchaseDeliveryRecord.getPurchaseApplicant());
                    purchaseSignFor.setAuditorName(purchaseDeliveryRecord.getAuditorName());
                    purchaseSignFor.setTotalAmount(purchaseDeliveryRecord.getTotalAmount());
                    listBig.add(purchaseSignFor);
                }
                /*    }else if(PurchaseSignUtil.SCR.equals(purchaseSignFor.getInventoryTypeCode())){ *///生产-报工单信息

            }else if(PurchaseSignUtil.SCR.equals(params.get("inventoryTypeCode"))){ //生产-报工单信息
            /*    ProductionTheWorkOrderVO productionWorkOrder = productionTheWorkOrderList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);*/
                ProductionTheWorkOrderVO productionWorkOrder = workOrderMap.get(purchaseSignFor.getSignTaskId());
                if(productionWorkOrder!=null){
                    purchaseSignFor.setLogisticsNo(productionWorkOrder.getCode());
                    purchaseSignFor.setSn(productionWorkOrder.getWorkOrderCode());
                    purchaseSignFor.setSupplierId(productionWorkOrder.getRoleId());
                    purchaseSignFor.setCorporateCode(productionWorkOrder.getRoleCode());
                    purchaseSignFor.setCorporateName(productionWorkOrder.getRoleName());
                    purchaseSignFor.setDeliveryCreatorName(productionWorkOrder.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(productionWorkOrder.getCreateTime());
                    purchaseSignFor.setPhone(productionWorkOrder.getPhone());
                    purchaseSignFor.setBusinessContact(productionWorkOrder.getUsername());
                    purchaseSignFor.setDepartmentName(productionWorkOrder.getRoleName());
                    listBig.add(purchaseSignFor);
                }else{
                    listBig.add(purchaseSignFor);
                }
            }
        }

        // 使用原始Page对象的总数信息
        Page<PurchaseSignForVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(listBig);

        return resultPage;
    }

    public Page<PurchaseSignForVO> paginateList(List<PurchaseSignForVO> list, int currentPage, int pageSize) {
        // 计算总记录数和总页数
        int totalRecords = list.size();
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        // 防止currentPage超出范围
        if(currentPage < 1) currentPage = 1;
        if(currentPage > totalPages) currentPage = totalPages;

        // 计算开始索引
        int startIndex = (currentPage - 1) * pageSize;
        // 结束索引
        int endIndex = Math.min(startIndex + pageSize, totalRecords);

        // 获取当前页的数据
        List<PurchaseSignForVO> pageContent = list.subList(startIndex, endIndex);

        // 创建并设置返回的Page对象
        Page<PurchaseSignForVO> pageResult = new Page<>(currentPage, pageSize);
        pageResult.setTotal(totalRecords);
        pageResult.setRecords(pageContent);

        return pageResult;
    }
    @Override
    public PurchaseSignForVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean delete(Long purchaseSignForId) {
        int i = baseMapper.deleteById(purchaseSignForId);
        if (i > 0) {
            purchaseSignForProductService.remove(new QueryWrapper<PurchaseSignForProduct>().eq("purchase_sign_for_id", purchaseSignForId));
        }
        return i > 0;
    }

    @Override
    @Transactional(readOnly = false)
    public boolean confirm(Long id) {
        // 查询采购入库类型的数据
        List<WarehouseInventoryTypeVO> warehouseInventoryTypes = baseMapper.queryWarehouseInventoryType(0, 1);
        if (warehouseInventoryTypes.size() == 0) {
            throw new BusinessException(300, "请添加采购入库的出入库类型");
        }
        WarehouseInventoryTypeVO warehouseInventoryTypeVO = new WarehouseInventoryTypeVO();
        for (WarehouseInventoryTypeVO warehouseInventoryType : warehouseInventoryTypes) {
            if (warehouseInventoryType.getName().equals("采购入库")) {
                warehouseInventoryTypeVO = warehouseInventoryType;
                break;
            }
        }
        if (warehouseInventoryTypeVO == null) {
            warehouseInventoryTypeVO = warehouseInventoryTypes.get(0);
        }

        PurchaseSignFor purchaseSignFor = baseMapper.selectById(id);
        if (purchaseSignFor == null) {
            throw new BusinessException(300, "参数错误");
        }
        purchaseSignFor.setStatus("2");// 已签收
        purchaseSignFor.setUpdateTime(LocalDateTime.now());
        purchaseSignFor.setModifier(JwtUtils.getLoginUserId());
        purchaseSignFor.setModifierName(JwtUtils.getLoginUsername());
        int i = baseMapper.updateById(purchaseSignFor);
        return i > 0;
    }

    @Override
    public PurchaseSignForVO getDeliverySignInfo(String signNo) {
        return baseMapper.getDeliverySignInfo(signNo);
    }

    @Override
    public InventoryJobLabelVO getSignPackLabelNum(Long signProductDetailId) {
        return baseMapper.getSignPackLabelNum(signProductDetailId);
    }

    @Override
    public PalletBoxListVO getPalletBox(String code, Long warehouseId) {
        return baseMapper.getPalletBox(code, warehouseId);
    }

    @Override
    public PurchaseSignForProductLabelVO getSignPackLabel(Long signId, String code, Integer inoutType, Long signProductDetailId) {
        return baseMapper.getSignPackLabel(signId, code, inoutType, signProductDetailId);
    }

    @Override
    public WarehouseShelfSpaceVO getShelfSpace(String code, Long warehouseId) {
        return baseMapper.getShelfSpace(code, warehouseId);
    }

    @Override
    public List<PurchaseSignForExportVO> exportList4app(Page page, Map<String, Object> params) {

        //采购-发货记录列表
        Map<String, Object> purchaseDeliveryRecordMap = new HashMap<>();
        purchaseDeliveryRecordMap.put("databaseUser", params.get("databaseUser"));
        List<PurchaseDeliveryRecordVO> purchaseDeliveryRecordList = purchaseDeliveryRecordDao.list4app(null, purchaseDeliveryRecordMap);
        //生产-报工单信息
        Map<String, Object> productionTheWorkOrderMap = new HashMap<>();
        productionTheWorkOrderMap.put("databaseUser", params.get("databaseUser"));
        List<ProductionTheWorkOrderVO> productionTheWorkOrderList = baseMapper.productionWorkOrderList(productionTheWorkOrderMap);

        //签收记录列表2
        List<PurchaseSignForVO> list = baseMapper.list4app(page, params);
        List<PurchaseSignForVO> listBig=new ArrayList<>();
        List<PurchaseSignForExportVO> exportVOArrayList=new ArrayList<>();

        for (PurchaseSignForVO purchaseSignFor : list) {
            //采购-发货记录信息
            if (PurchaseSignUtil.CGR.equals(purchaseSignFor.getInventoryTypeCode())) {
                PurchaseDeliveryRecordVO purchaseDeliveryRecord = purchaseDeliveryRecordList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);
                if(purchaseDeliveryRecord != null){
                    purchaseSignFor.setLogisticsNo(purchaseDeliveryRecord.getLogisticsNo());
                    purchaseSignFor.setSupplierId(purchaseDeliveryRecord.getSupplierId());
                    purchaseSignFor.setSn(purchaseDeliveryRecord.getSn());
                    purchaseSignFor.setCorporateCode(purchaseDeliveryRecord.getCorporateCode());
                    purchaseSignFor.setCorporateName(purchaseDeliveryRecord.getCorporateName());
                    purchaseSignFor.setTransportMode(purchaseDeliveryRecord.getTransportMode());
                    purchaseSignFor.setTransportModeDesc(purchaseDeliveryRecord.getTransportModeDesc());
                    purchaseSignFor.setLogisticsCompany(purchaseDeliveryRecord.getLogisticsCompany());
                    purchaseSignFor.setEnterType(purchaseDeliveryRecord.getEnterType());
                    purchaseSignFor.setEnterTypeName(purchaseDeliveryRecord.getEnterTypeName());
                    purchaseSignFor.setDeliveryCreatorName(purchaseDeliveryRecord.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(purchaseDeliveryRecord.getCreateTime());
                    purchaseSignFor.setWaybillNo(purchaseDeliveryRecord.getWaybillNo());
                    purchaseSignFor.setPlateNo(purchaseDeliveryRecord.getPlateNo());
                    purchaseSignFor.setCourierNo(purchaseDeliveryRecord.getCourierNo());
                    purchaseSignFor.setPhone(purchaseDeliveryRecord.getPhone());
                    purchaseSignFor.setBusinessContact(purchaseDeliveryRecord.getBusinessContact());
                    purchaseSignFor.setDepartmentName(purchaseDeliveryRecord.getDepartmentName());
                    purchaseSignFor.setPurchaseApplicant(purchaseDeliveryRecord.getPurchaseApplicant());
                    purchaseSignFor.setAuditorName(purchaseDeliveryRecord.getAuditorName());
                    purchaseSignFor.setTotalAmount(purchaseDeliveryRecord.getTotalAmount());
                    listBig.add(purchaseSignFor);
                }else{
                    listBig.add(purchaseSignFor);
                }
            }else if(PurchaseSignUtil.SCR.equals(purchaseSignFor.getInventoryTypeCode())){  ///生产-报工单信息
                ProductionTheWorkOrderVO productionWorkOrder = productionTheWorkOrderList.stream().filter(t -> t.getId() == purchaseSignFor.getSignTaskId()).findFirst().orElse(null);
                if(productionWorkOrder!=null){
                    purchaseSignFor.setLogisticsNo(productionWorkOrder.getCode());
                    purchaseSignFor.setSn(productionWorkOrder.getWorkOrderCode());
                    purchaseSignFor.setSupplierId(productionWorkOrder.getRoleId());
                    purchaseSignFor.setCorporateCode(productionWorkOrder.getRoleCode());
                    purchaseSignFor.setCorporateName(productionWorkOrder.getRoleName());
                    purchaseSignFor.setDeliveryCreatorName(productionWorkOrder.getCreatorName());
                    purchaseSignFor.setDeliveryCreateTime(productionWorkOrder.getCreateTime());
                    purchaseSignFor.setPhone(productionWorkOrder.getPhone());
                    purchaseSignFor.setBusinessContact(productionWorkOrder.getUsername());
                    purchaseSignFor.setDepartmentName(productionWorkOrder.getRoleName());
                    listBig.add(purchaseSignFor);
                }else{
                    listBig.add(purchaseSignFor);
                }
            }else{
                listBig.add(purchaseSignFor);
            }

            PurchaseSignForExportVO purchaseSignForExportVO=new PurchaseSignForExportVO();
            BeanUtils.copyProperties(purchaseSignFor, purchaseSignForExportVO);
            exportVOArrayList.add(purchaseSignForExportVO);
        }
        return exportVOArrayList;
    }


}
